package cm.example.shoppingplatformspringboot.service;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.StatObjectArgs;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Service
public class MinioService {
    @Resource
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.endpoint}")
    private String endpoint;

    public String uploadFile(@NotNull MultipartFile file) throws Exception {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = generateFileName(originalFilename);

        // 执行上传
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .contentType(file.getContentType())
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build()
        );

        // 返回文件URL
        return getFileUrl(fileName);
    }

    public String getFileUrl(String fileName){
        return endpoint + "/" + bucketName + "/" + fileName;
    }

    public boolean isFileExist(String fileName) {
        try {
            minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public void deleteFile(String fileName) throws Exception {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build()
        );
    }

    public void safeDeleteFile(String fileUrl) {
        try {
            // 精确匹配 URL 格式：http://endpoint/bucketName/fileName
            String expectedPrefix = endpoint + "/" + bucketName + "/";
            if (!fileUrl.startsWith(expectedPrefix)) {
                return;
            }

            // 提取纯文件名（兼容URL编码）
            String encodedFileName = fileUrl.substring(expectedPrefix.length());
            String fileName = URLDecoder.decode(encodedFileName, StandardCharsets.UTF_8); // 处理特殊字符

            if (isFileExist(fileName)) {
                deleteFile(fileName);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    private String generateFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extension = "";

        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        return uuid + extension;
    }
}
